<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category RoleService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/20  16:51
 * +--------------------------------------------------------+
 */

namespace App\Services;


use App\Exceptions\ResponseException;
use App\Models\Admin;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RoleService extends BaseService
{
    protected $admin;
    protected $role;

    public function __construct()
    {

        $this->role = new Role();
    }

    /**
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  11:01
     */
    public function getAll()
    {
        return $this->role->query()->select('id','name','display_name','guard_name')->get()->toArray();
    }

    /**
     * @param $id
     * @return Builder|Builder[]|Collection|Model|null
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  14:10
     */
    public function getOne($id)
    {
        return $this->role->query()->select('id','name','display_name','guard_name')->find($id);
    }

    /**
     * @param $params
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  14:11
     */
    public function getList($params)
    {
        $query   = $this->role->query();
        $perPage = $this->perPage($params);
        if (!empty($params['field']) && !empty($params['order'])) {
            $query = $query->orderBy($params['field'], $params['order']);
        }
        if (!empty($params['name'])) {
            $query = $query->where('display_name', 'like', '%' . $params['name'] . '%');
        }
        if (!empty($params['created_at'])) {
            $times = explode(' - ', $params['created_at']);
            $query = $query->whereBetween('created_at', $times);
        }

        $list = $query->paginate($perPage)->toArray();

        return return_success_msg(ResponseException::REQUEST_SUCCESS_MESSAGE, $list);
    }

    /**
     * @param $params
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  14:18
     */
    public function addData($params)
    {
        $data['display_name'] = $params->display_name;
        $data['name']         = $params->name;
        $data['guard_name']   = 'admin';

        DB::beginTransaction();
        try {
            $role = $this->role->create($data);
            if (false == $role) {
                DB::rollBack();
                return return_error_msg(ResponseException::ERROR_ADD_MESSAGE);
            }
            $permission     = Permission::query()->whereIn('id', $params->permission_id)->get();
            $addPermissions = $role->syncPermissions($permission);
        } catch (\Exception $e) {
            DB::rollBack();
            return return_error_msg(exception_msg($e->getMessage()));
        }

        if ($addPermissions) {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_ADD_MESSAGE);
        } else {
            DB::rollBack();
            return return_error_msg(ResponseException::ERROR_ADD_MESSAGE);
        }
    }

    /**
     * @param $params
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  14:25
     */
    public function editData($params)
    {
        $id   = $params->id;
        $role = $this->role->query()->find($id);
        if (false == $role) {
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }
        try {
            $role->display_name = $params->display_name;
            $role->name         = $params->name;
            $role               = $role->save();
        } catch (\Exception $e) {
            DB::rollBack();
            return return_error_msg(exception_msg($e->getMessage()));
        }

        $permission     = Permission::whereIn('id', $params->permission_id)->get();
        $addPermissions = $role->syncPermissions($permission);

        if ($addPermissions) {
            DB::rollBack();
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        } else {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        }
    }

    /**
     * @param $ids
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  14:33
     */
    public function delData($ids)
    {
        if (is_string($ids)) {
            $ids = [$ids];
        }
        if (in_array(1,$ids)) {
            return return_error_msg('超级管理员不能删除');
        }

        $data = $this->role->query()->whereIn('id', $ids)->get();
        if (empty($data)) {
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }

        DB::beginTransaction();
        try {
            foreach ($data as $value) {
                $count = Admin::role($value->name)->count();
                if ($count > 0){
                    DB::rollBack();
                    return return_error_msg('角色已配置管理员，无法删除');
                }
                $addPermissions = $value->syncPermissions([]);
                $del            = $value->delete();
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return return_error_msg(exception_msg($e->getMessage()));
        }

        if ($del) {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_DELETE_MESSAGE);
        } else {
            DB::rollBack();
            return return_error_msg(ResponseException::ERROR_DELETE_MESSAGE);
        }

    }

}
